﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace crawler
{
    public partial class Form1 : Form
    {
        Thread thread = null;
        Crawler crawler = null;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (thread != null && thread.IsAlive) thread.Abort();
            if (crawler != null) crawler = new Crawler();
            textBox2.Clear();
            textBox2.AppendText("爬虫已启动" + "\r\n");
            crawler = new Crawler();
            crawler.Stopped += Stopped;
            crawler.Downloaded += PrintDownloadStatus;
            crawler.startUrl = textBox1.Text;
            Match match = Regex.Match(crawler.startUrl, @"^(?<url>https?://(?<host>(www.)?[-a-zA-Z0-9@:%._+~#=]{1,256})/?(.*/)*(?<file>(.*(.html|.jsp|.aspx))?))$");
            if (match.Length == 0) return;
            crawler.hostFilter = match.Groups["host"].Value + "$";
            crawler.fileFilter = "(.html|.jsp|.aspx)?$";
            thread = new Thread(crawler.Start);
            thread.Start();
        }
        private void Stopped()
        {
            Action action = () => textBox2.AppendText("爬虫已停止..." + "\r\n");
            if (InvokeRequired) Invoke(action);
            else action();
        }
        private void PrintDownloadStatus(string url, string message)
        {
            string info = $"网页：{url} [状态：{message}]";
            Action action = () => textBox2.AppendText(info + "\r\n");
            if (InvokeRequired) Invoke(action);
            else action();
        }
    }
}